import { useState, useEffect } from 'react'
import './App.css'
import { fetchTodos } from './api'
import 'antd/dist/antd.css' // 引入UI框架样式
import { Spin, Tabs } from 'antd'
import TodoList from './components/TodoList'
import TodoInput from './components/TodoInput'


const { TabPane } = Tabs

function App() {
  const [todos, setTodos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeKey, setActiveKey] = useState('全部')
  const [placeholder, setPlaceholder] = useState('')
  const [query, setQuery] = useState('') // 做筛选
  const onSetQuery = (query) => {
    console.log(query)
    setQuery(query)
  }
  const onDelete = (id) => {
    // console.log(id)
    let newTodes = todos.filter(todo => todo.id != id)
    setTodos([
      ...newTodes
    ])
  }
  useEffect(() => {
    // useEffect 不只是做生命周期的onload，还可以做更新事件
    // 当[activeKey, query]发生改变，useEffect执行显示更新
    setLoading(true)
    fetchTodos({ query: query, tab: activeKey })
      .then((data) => {
        // console.log(data);
        setTodos([...data.result]);
        setLoading(false);
      })
    // console.log('当[activeKey, query]发生改变useEffect执行更新')
  }, [activeKey, query])
  useEffect(() => {
    // onload/update
    setLoading(true)
    setPlaceholder(`在${activeKey}内搜索`)
  }, [activeKey])
  // useEffect(() => {
  //   // 请求数据
  //   // setLoading(true)
  //   // fetchTodos ？ 参数对象来组织
  //   fetchTodos({ query: 'todo', tab: '全部' })
  //     .then((data) => {
  //       // console.log(data);
  //       setTodos([...data.result]);
  //       setLoading(false);
  //     })
  // }, [])
  return (
    <>
      {/* 70%的通用业务组件，属于框架提供 */}
      <Tabs activeKey={activeKey} onChange={setActiveKey}>
        <TabPane tab='全部' key='全部' />
        <TabPane tab='已完成' key='已完成' />
        <TabPane tab='未完成' key='未完成' />
      </Tabs>
      <div className="app-wrap">
        {/* wrap 包裹，容器 */}
        <h1 className='app-title'>Todo List</h1>
        <TodoInput placeholder={placeholder} onSetQuery={onSetQuery} />
        <Spin spinning={loading} tip='加载中~'>
          {/* 业务组件， 显示任务列表 */}
          <TodoList todos={todos} onDelete={onDelete} />
        </Spin>
      </div>
    </>
  )
}

export default App
